package com.cjjd.c.http;

import android.content.Context;

import com.cjjd.c.App;
import com.cjjd.c.BuildConfig;
import com.cjjd.c.utils.LogUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/2/23.
 */
public class RetrofitSingleton {

    private static Retrofit retrofit = null;
    private static RetrofitInterface service;
    private static OkHttpClient okHttpClient;

    private RetrofitSingleton() {
        if (retrofit != null) {
            service = retrofit.create(RetrofitInterface.class);
        } else {
            init(App.getContext());
        }
    }

    /**
     * 初始化
     *
     * @param context
     */
    public static void init(Context context) {

        // 拦截器
        Interceptor mTokenInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request originalRequest = chain.request();
                Request.Builder requestBuilder = originalRequest.newBuilder();

                // 每个接口都添加以下参数
                HttpUrl originalHttpUrl = originalRequest.url();
                HttpUrl url = originalHttpUrl.newBuilder()
//                        .addQueryParameter("equipmentType", Build.DEVICE)
//                        .addQueryParameter("source", "ANDROID")
//                        .addQueryParameter("os", "APP_Android")
//                        .addQueryParameter("dtimes", System.currentTimeMillis() + "")
                        .build();

                requestBuilder.url(url);

                return chain.proceed(requestBuilder.build());
            }
        };

        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
        // 添加log信息的拦截器
        if (BuildConfig.LOG_DEBUG) {
            okBuilder.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            LogUtil.e("okhttp_xyd_add", message);
                        }
                    }).setLevel(HttpLoggingInterceptor.Level.BODY)
            );
//
//            okBuilder.addInterceptor(new LogInterceptor());
        }

        okBuilder.retryOnConnectionFailure(false)
                .readTimeout(90, TimeUnit.SECONDS)        //设置读取超时时间
                .writeTimeout(90, TimeUnit.SECONDS)       //设置写的超时时间
                .connectTimeout(90, TimeUnit.SECONDS)     //设置连接超时时间
                .addNetworkInterceptor(mTokenInterceptor)
                .authenticator(new TokenAuthenticator());

        okHttpClient = okBuilder.build();
        // ================================================================


        retrofit = new Retrofit.Builder()
                .baseUrl(Url.HOST_BASE)
                .client(okHttpClient)
                .addConverterFactory(StringConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                //.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        service = retrofit.create(RetrofitInterface.class);
    }


    //获取单例
    public static RetrofitSingleton getInstance() {
        return new RetrofitSingleton();
    }

    public static OkHttpClient getOkHttpClient(){
        if (okHttpClient==null) init(App.getContext());;
        return okHttpClient;
    }


    public static Retrofit getRetrofit(Context context) {
        if (retrofit != null) return retrofit;
        init(context);

        return getRetrofit(context);
    }

    public static RetrofitInterface getService(Context context) {
        if (service != null) return service;
        init(context);
        return getService(context);
    }


}
